%------------------------------------------------------------------
%------------------------------------------------------------------
%   Author: Md. Sazzad Hussain (sazzad.hussain@sydney.edu.au)
%   Learning and Affect Technologies Engineering
%   University of Sydney, 2010
%------------------------------------------------------------------
%------------------------------------------------------------------

function [featExt] = autoTutorFeatEx(subjectID,filesPath,winSizeECG,winSizeGSR,... 
winSizeEMG,winSizeResp,sRate,dSample,outdir,opSys,dubug)
% %%Sync & Feature Extraction Program (AutoTutor Physio Data)
%channels: ECG, EMG, GSR, Resp

warning off;
if opSys==1
    sep='/';
elseif opSys==2
    sep='\';
end

filesDir=dir(filesPath);%dir info for files path
x=1;
y=1;
for m=1:length(filesDir)
    [path,name,ext,ver] = fileparts(filesDir(m).name);
    for n=1:length(subjectID(:,1))
        if strncmp(subjectID(n,:),name,27)%choose only selected subjects
            if strcmp(ext,'.mat')%.mat files
                loadPhysio(x,:)=[filesPath sep name ext];%.mat physio path
                physioSplit(x,:)= regexp(name,'_','split');
                physioATS=physioSplit(:,5);%physio abs time stamp
                x=x+1;
            elseif strcmp(ext, '.txt')%.txt files
                loadAnn(y,:)=[filesPath sep  name ext];%.txt annotation path
                annSplit(y,:)= regexp(name,'_','split');
                annATS=annSplit(:,5);%physio abs time stamp
                y=y+1;
            end
        end
    end
end

% mkdir(outdir);%create directory for features (.mat)
for j=1:(x-1)
    load(loadPhysio(j,:));%load physio file
    
    loadAnn(j,:)
    fid = fopen(loadAnn(j,:));%load annotation
    
    data=downsample(data,dSample);%-->down sample all physio channels
    nsRate=(sRate/dSample);%new sample rate
   
    C = textscan(fid,'%f%f%f%s%f','delimiter', ',');
    fclose(fid);
    
    subjectFeatDir=[outdir];
    mkdir(subjectFeatDir);%create directory for features (.mat)
    Absolute_Time_physio = datenum(physioATS(j), 'HH-MM-SS')*24*60*60; %in seconds
    Absolute_Time_ann= datenum(annATS(j), 'HH-MM-SS')*24*60*60; %in seconds
    
    annStart_sec=C{2};%col for start time seconds    
    k = 1;
    featmat = [];
    featmatECG = [];
    featmatGSR = [];
    featmatEMG = [];
    featmatRESP = [];
    catSelfVec=[];
    valSelfVec=[];
    arSelfVec=[];
    dimSelfVec=[];
    
    lenPhysio=length(data);%length of physio data
    %GSR preprocessing
    dataGSR = aubt_lowpassFilter (data(:,2), nsRate, 0.3);
    dataGSR = aubt_scBaseline (dataGSR);

    while k <= length (annStart_sec)
        start_times = Absolute_Time_ann + annStart_sec(k);
        Start_Trial = start_times;
        Start_Index = (Start_Trial - Absolute_Time_physio) * nsRate; %start time
                
        End_IndexECG = (Start_Index + winSizeECG * nsRate)-1;%end time for ecg window
        End_IndexGSR = (Start_Index + winSizeGSR * nsRate)-1;%end time for gsr window
        End_IndexEMG = (Start_Index + winSizeEMG * nsRate)-1;%end time for emg window
        End_IndexResp = (Start_Index + winSizeResp * nsRate)-1;%end time for resp window
        
        if lenPhysio<max([End_IndexECG End_IndexGSR End_IndexEMG End_IndexResp])
            break;
        end    
     
        Trial_ChunkECG = data(Start_Index:End_IndexECG,1); %trial chunk
        Trial_ChunkGSR = dataGSR(Start_Index:End_IndexGSR); %trial chunk
        Trial_ChunkEMG1 = data(Start_Index:End_IndexEMG,3); %trial chunk
        Trial_ChunkEMG2 = data(Start_Index:End_IndexEMG,5); %trial chunk
        Trial_ChunkResp = data(Start_Index:End_IndexResp,6); %trial chunk
        
        %plot channels
        if dubug==1
            pause(0.2)
            subplot(5,1,1),plot(Trial_ChunkECG);
            subplot(5,1,2),plot(Trial_ChunkGSR);
            subplot(5,1,3),plot(Trial_ChunkEMG1);
            subplot(5,1,4),plot(Trial_ChunkEMG2);
            subplot(5,1,5),plot(Trial_ChunkResp);
        end
        
        ecgAffect= Trial_ChunkECG;%ecg data
        gsrAffect= Trial_ChunkGSR;%gsr data
        emg1Affect= Trial_ChunkEMG1;%emg1 data
        emg2Affect= Trial_ChunkEMG2;%emg2 data
        respAffect= Trial_ChunkResp;%resp data
        
        %feature extraction
        [ECGfeatvc ECGfeatnames GSRfeatvc GSRfeatnames EMG1featvc...
            EMG1featnames EMG2featvc EMG2featnames RESPfeatvc...
            RESPfeatnames] = aubtProxy(ecgAffect, gsrAffect, emg1Affect,...
            emg2Affect, respAffect, nsRate);
        
        featvc = [ECGfeatvc,GSRfeatvc,EMG1featvc,EMG2featvc,RESPfeatvc];
        featmat = [featmat;featvc];
        
        %featmat individual for channels
        featvcECG=[ECGfeatvc];
        featmatECG=[featmatECG;featvcECG];
        featvcGSR=[GSRfeatvc];
        featmatGSR=[featmatGSR;featvcGSR];
        featvcEMG=[EMG1featvc, EMG2featvc];
        featmatEMG=[featmatEMG;featvcEMG];
        featvcRESP=[RESPfeatvc];
        featmatRESP=[featmatRESP;featvcRESP];
        
        %extracting categories
        catSelf=C{4}(k);
        catSelfVec = [catSelfVec;catSelf];
        
        %extracting self report dimensions
        switch C{5}(k)
            case 1
                valSelf={'MediumValence'};
                arSelf={'LowArousal'};
                dimSelf={'MediumValence-LowArousal'};
            case 2
                valSelf={'HighValence'};
                arSelf={'LowArousal'};
                dimSelf={'HighValence-LowArousal'};
            case 3
                valSelf={'MediumValence'};
                arSelf={'MediumArousal'};
                dimSelf={'MediumValence-MediumArousal'};
            case 4
                valSelf={'HighValence'};
                arSelf={'MediumArousal'};
                dimSelf={'HighValence-MediumArousal'};
            case 5
                valSelf={'HighValence'};
                arSelf={'HighArousal'};
                dimSelf={'HighValence-HighArousal'};
            case 6
                valSelf={'MediumValence'};
                arSelf={'HighArousal'};
                dimSelf={'MediumValence-HighArousal'};
            case 7
                valSelf={'LowValence'};
                arSelf={'HighArousal'};
                dimSelf={'LowValence-HighArousal'};
            case 8
                valSelf={'LowValence'};
                arSelf={'MediumArousal'};
                dimSelf={'LowValence-MediumArousal'};
            case 9
                valSelf={'LowValence'};
                arSelf={'LowArousal'};
                dimSelf={'LowValence-LowArousal'};
        end
        valSelfVec = [valSelfVec;valSelf];
        arSelfVec = [arSelfVec;arSelf];
        dimSelfVec = [dimSelfVec;dimSelf];
        subjectID(j,:)
        k = k+ 1
    end
    featmat = num2cell(featmat);
    featMatClass = [featmat,catSelfVec,dimSelfVec,valSelfVec,arSelfVec];
    featnames = [ECGfeatnames,GSRfeatnames,strcat(EMG1featnames,'_corr'),strcat(EMG2featnames,'_zym'),RESPfeatnames,...
        'SelfCategory', 'SelfDimension','SelfValence','SelfArousal'];
    data_set = [featnames;featMatClass];
%     save all features
    CELL2CSV([subjectFeatDir, sep ,subjectID(j,:),'_autoTutor.csv'],data_set,',');
    
%     %save for individual channels
%     featmatECG = num2cell(featmatECG);
%     featmatGSR = num2cell(featmatGSR);
%     featmatEMG = num2cell(featmatEMG);
%     featmatRESP = num2cell(featmatRESP);
%     
%     featMatClassECG = [featmatECG,valCatVec,arCatVec];
%     featMatClassGSR = [featmatGSR,valCatVec,arCatVec];
%     featMatClassEMG = [featmatEMG,valCatVec,arCatVec];
%     featMatClassRESP = [featmatRESP,valCatVec,arCatVec];
%     
%     featnamesECG = [ECGfeatnames,'CatValence','CatArousal'];
%     featnamesGSR = [GSRfeatnames,'CatValence','CatArousal'];
%     featnamesEMG = [strcat(EMG1featnames,'_corr'),strcat(EMG2featnames,'_zym'),'CatValence','CatArousal'];
%     featnamesRESP = [RESPfeatnames,'CatValence','CatArousal'];
%     
%     data_setECG = [featnamesECG;featMatClassECG];
%     data_setGSR = [featnamesGSR;featMatClassGSR];
%     data_setEMG = [featnamesEMG;featMatClassEMG];
%     data_setRESP = [featnamesRESP;featMatClassRESP];
    
%     %save ECG
%     CELL2CSV([subjectFeatDir, '/',subjectID(j,:),'_ecg.csv'],data_setECG,',');
%     %saveGSR
%     CELL2CSV([subjectFeatDir, '/',subjectID(j,:),'_gsr.csv'],data_setGSR,',');
%     %save EMG
%     CELL2CSV([subjectFeatDir, '/',subjectID(j,:),'_emg.csv'],data_setEMG,',');
%     %save Resp
%     CELL2CSV([subjectFeatDir, '/',subjectID(j,:),'_resp.csv'],data_setRESP,',');
end
clear all;
featExt=1;